package com.ikaros.concurrency.example.syn;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class SynchronizedCodeAndMethod {
    //修饰代码块
    private void expCode() {
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                log.info("expCode-{}", i);
            }
        }
    }

    //修饰方法
    private synchronized void expMethod() {
        for (int i = 0; i < 10; i++) {
            log.info("expMethod-{}", i);
        }
    }

    public static void main(String[] args) {
        SynchronizedCodeAndMethod synchronizedExp = new SynchronizedCodeAndMethod();
        SynchronizedCodeAndMethod synchronizedExpTwo = new SynchronizedCodeAndMethod();

        ExecutorService executorService = Executors.newCachedThreadPool();
        //修饰代码块和修饰方法【不同对象】可以进行多线程  同一对象单线程执行->作用于调用对象
        //ps:如果SynchronizedExp为父类,继承该类的子类调用父类的方法synchronized关键字无效
        executorService.execute(() -> {
            synchronizedExp.expCode();
        });
        executorService.execute(() -> {
            synchronizedExpTwo.expCode();
        });
    }
}
